$(document).ready(function()
{
  var worldNodes = new Array();
  var worldObjects = new Array();
  var worldSize = {
    width: 0,
    height: 0
  };
  var viewPort = {
    width: 7,
    height: 7
  }
  
  function initWorld(callback){
    $.ajax({
      url: 'javascripts/world.json',
      dataType: "json",
      error: function(jqXHR, textStatus, errorThrown){
        console.dir(errorThrown);
      },
      success: function(data, textStatus, jqXHR){
        var world = data.world;
        worldSize.height = world.floor.length;
        worldSize.width = world.floor[0].length;
        
        for(var i = 0; i < world.floor.length; i++){
          worldNodes.push(new Array());
          for(var j = 0; j < world.floor[0].length; j++){
            var fieldClass = "grass";
             switch(world.floor[i][j]){
               case "g":
                fieldClass = "grass";
                break;
               case "s":
                fieldClass = "stone";
                break;
               case "r":
                fieldClass = "river";
                break; 
               case "streetv":
                fieldClass = "streetv";
                break;
              case "streeth":
                fieldClass = "streeth";
                break;
              case "streettl":
                fieldClass = "streettl";
                break;
              case "streettr":
                fieldClass = "streettr";
                break;
              case "streetbl":
                fieldClass = "streetbl";
                break;
              case "streetbr":
                fieldClass = "streetbr";
                break;
             }
             var node = document.createElement("span");
             $(node).addClass("field");
             $(node).addClass(fieldClass);
             $(node).css({width: config.fieldWidth, height: config.fieldWidth, display: "block", float: "left"});
             
             $("#world").append(node);
             worldNodes[i].push(node);
          }
          $("#world").append("<br />");
        }
        $("#world").css("width", worldSize.width * 50);
        $("#viewport").css("width", viewPort.width * 50);
        $("#viewport").css("height", viewPort.height * 50);
        $("#world").append("<div class='clear'></div>");
        callback(data);
      }
    });
  }
  
  function causesCollision(object, newPos){
    
    for(var i = 0; i < worldObjects.length; i++){      
      var obj = worldObjects[i];
      if(
          (obj.position[0] == newPos[0]) && 
          (obj.position[1] == newPos[1]) && 
          (obj.collision == true) &&
          (object.collision == true)
        ){
          console.log("HEY da darfst du nicht hin!(" + obj.type  + " steht im Weg)");
          return true;
        }
    }
    return false;
  }
  
  function movePlayer(player, direction, callback){
      var newProps = {};
      var viewPortNewProps = {};
      var newPos = new Array(player.position[0], player.position[1]);
      switch(direction){
        case "left":
          newProps.left = "-=50";
          viewPortNewProps.left = "+=50";
          newPos[0]--;
          break;
        case "right":
          newProps.left = "+=50";
          viewPortNewProps.left = "-=50";
          newPos[0]++;
          break;
        case "up":
          newProps.top = "-=50";
          viewPortNewProps.top = "+=50";
          newPos[1]--;
          break;
        case "down":
          newProps.top = "+=50";
          viewPortNewProps.top = "-=50";
          newPos[1]++;
          break;
      }
      
      $(player.node).css("background-image", "url(images/guiproto/player-" + direction + ".png)");
      
      // make sure the player does not move out of his bounds
      if((newPos[0] >= worldSize.width) ||
         (newPos[0] < 0) ||
         (newPos[1] >= worldSize.height) ||
         (newPos[1] < 0)){
           callback();
      }else{
        if(!causesCollision(player, newPos)){
          player.position = newPos;
          // move the player
          $(player.node).animate(newProps, {duration: 300, easing: "linear", complete: callback});
          // move the viewport
          $("#world").animate(viewPortNewProps, {duration: 300, easing: "linear"}); 
        }else{
          callback();
        }
      }
  }
  
  function createObject(object){
    
    var node = document.createElement("div");
    $("#world").append(node);
    $(node).css("left", object.position[0] * 50);
    $(node).css("top", object.position[1] * 50);
    object.node = node;
    worldObjects.push(object);
    
    return object;
  }
  
  function createPlayer(player){
    
    var player = createObject(player);
    $(player.node).addClass("player");
    
    var keydownFunc = function(event){
      var direction = null;
      switch(event.which){
        case 37:
          direction = "left";
          break;
        case 38:
          direction = "up";
          break;
        case 39:
          direction = "right";
          break;
        case 40:
          direction = "down";
          break;
      }
      
      if(direction != null){
        // disable keydown listening until the movement is done
        $(document).unbind("keydown");
        movePlayer(player, direction, function(){
          $(document).keydown(keydownFunc);
        }); 
      }
    };
    
    $(document).keydown(keydownFunc);
    // ajust the viewport so that the player is in the middle of the screen
    var newLeft = (player.position[0] - Math.floor(viewPort.width/2)) * -50;
    var newTop = (player.position[1] - Math.floor(viewPort.height/2)) * -50;
    $("#world").css({left: newLeft, top: newTop}); 
  }
  
  function createRock(rock){
    var rock = createObject(rock);
    $(rock.node).addClass("rockObject");
  }
  
  function createBlocker(blocker){
    var blocker = createObject(blocker);
    $(blocker.node).addClass("blockerObject");
  }
  
  initWorld(function(data){
    // place objects:
    for(var i = 0; i < data.world.objects.length; i++){
      switch(data.world.objects[i].type){
        case "player":
          createPlayer(data.world.objects[i]);
          break;
        case "stone":
          createRock(data.world.objects[i]);
          break;
        case "blocker":
          createBlocker(data.world.objects[i]);
          break;
      }
    }
  });
});